<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="common.jsp" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <style>
        /* 隐藏滚动条但可以滚动 */
        body {
            overflow: hidden;
        }
        .container-fluid {
            overflow-y: scroll;
            height: 100vh; /* 高度设置为全屏 */
        }
    </style>
    <script>
        $(document).ready(function() {
            loadUsers(1); // 页面加载时加载第一页用户数据
        });

        function loadUsers(page) {
            var keyword = $('#searchInput').val().trim();
            $.ajax({
                type: 'GET',
                url: '${pageContext.request.contextPath}/user',
                data: {
                    operation: 'findByKeyword',
                    keyword: keyword,
                    page: page,
                    pageSize: 5 // 每页显示的数据条数，根据实际需求调整
                },
                dataType: 'json',
                success: function(response) {
                    $('#userTableBody').empty();
                    $('#pagination').empty();

                    $.each(response.data, function(index, user) {
                        $('#userTableBody').append(
                            '<tr>' +
                            '<td>' + user.id + '</td>' +
                            '<td>' + user.username + '</td>' +
                            '<td>' + user.nickname + '</td>' +
                            '<td><img src="' + user.avatar + '" alt="头像" class="img-thumbnail" width="50" height="50"></td>' +
                            '<td>' + user.roleType + '</td>' +
                            '<td>' +
                            '<button onclick="editUser(this)" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#editUserModal">编辑</button> ' +
                            '<button onclick="deleteUser(' + user.id + ')" class="btn btn-danger btn-sm">删除</button>' +
                            '</td>' +
                            '</tr>'
                        );
                    });

                    var totalPages = Math.ceil(response.other / 5);
                    for (var i = 1; i <= totalPages; i++) {
                        $('#pagination').append(
                            '<li class="page-item ' + (page === i ? 'active' : '') + '">' +
                            '<a class="page-link" href="#" onclick="loadUsers(' + i + ')">' + i + '</a>' +
                            '</li>'
                        );
                    }
                },
                error: function(xhr, status, error) {
                    console.error('加载用户数据出错:', error);
                }
            });
        }

        function searchUsers() {
            loadUsers(1);
        }

        function editUser(row) {
            var $row = $(row).closest('tr'); // 获取当前行
            var userId = $row.find('td:eq(0)').text();
            var username = $row.find('td:eq(1)').text();
            var nickname = $row.find('td:eq(2)').text();
            var avatar = $row.find('td:eq(3) img').attr('src');
            var roleType = $row.find('td:eq(4)').text();

            $('#editUserId').val(userId);
            $('#editUsername').val(username);
            $('#editNickname').val(nickname);
            $('#editAvatar').attr('src', avatar);
            $('#editRoleType').val(roleType);

            $('#editUserModal').modal('show'); // 显示模态框
        }

        function uploadAvatar(fileInput) {
            var formData = new FormData();
            formData.append('file', fileInput.files[0]);

            $.ajax({
                type: 'POST',
                url: '${pageContext.request.contextPath}/file/upload',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    $('#editAvatar').attr('src', response); // 更新头像预览
                    $('#editAvatarInput').val(response); // 更新隐藏的头像 URL 输入框
                },
                error: function(xhr, status, error) {
                    console.error('上传头像出错:', error);
                }
            });
        }

        function saveUser() {
            var userId = $('#editUserId').val();
            var username = $('#editUsername').val();
            var nickname = $('#editNickname').val();
            var avatar = $('#editAvatarInput').val();
            var roleType = $('#editRoleType').val();

            $.ajax({
                type: 'POST',
                url: '${pageContext.request.contextPath}/user',
                data: {
                    operation: 'updateUser',
                    userId: userId,
                    username: username,
                    nickname: nickname,
                    avatar: avatar,
                    roleType: roleType
                },
                dataType: 'json',
                success: function(response) {
                    $('#editUserModal').modal('hide');
                    loadUsers(1); // 刷新用户列表
                },
                error: function(xhr, status, error) {
                    console.error('更新用户信息出错:', error);
                }
            });
        }

        function deleteUser(userId) {
            if (confirm('确定要删除该用户吗？')) {
                $.ajax({
                    type: 'POST',
                    url: '${pageContext.request.contextPath}/user',
                    data: {
                        operation: 'deleteUser',
                        userId: userId
                    },
                    dataType: 'json',
                    success: function(response) {
                        loadUsers(1); // 刷新用户列表
                    },
                    error: function(xhr, status, error) {
                        console.error('删除用户出错:', error);
                    }
                });
            }
        }
    </script>
</head>
<body>
<div class="container-fluid mt-4">

    <!-- 搜索框 -->
    <div class="input-group mb-3">
        <input type="text" id="searchInput" class="form-control" placeholder="输入关键字搜索">
        <div class="input-group-append">
            <button class="btn btn-primary" type="button" onclick="searchUsers()">搜索</button>
        </div>
    </div>

    <!-- 用户表格和分页 -->
    <table id="userTable" class="table table-bordered table-hover" >
        <thead>
        <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>昵称</th>
            <th>头像</th>
            <th>角色类型</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="userTableBody">
        <!-- 用户数据将会动态填充在这里 -->
        </tbody>
    </table>
    <nav aria-label="Page navigation">
        <ul class="pagination" id="pagination">
            <!-- 分页导航将会动态生成在这里 -->
        </ul>
    </nav>
</div>

<!-- 编辑用户的模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editUserModalLabel">编辑用户</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="editUserId" name="userId">
                    <div class="form-group">
                        <label for="editUsername">用户名</label>
                        <input type="text" class="form-control" id="editUsername" name="username" readonly>
                    </div>
                    <div class="form-group">
                        <label for="editNickname">昵称</label>
                        <input type="text" class="form-control" id="editNickname" name="nickname">
                    </div>
                    <div class="form-group">
                        <label for="editAvatarFile">头像</label>
                        <input type="file" class="form-control-file" id="editAvatarFile" name="avatar" onchange="uploadAvatar(this)">
                        <img id="editAvatar" class="img-thumbnail mt-2" width="100" height="100" src="#" alt="头像预览">
                        <input type="hidden" id="editAvatarInput" name="avatar">
                    </div>
                    <div class="form-group">
                        <label for="editRoleType">角色类型</label>
                        <input type="text" class="form-control" id="editRoleType" name="roleType">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
            </div>
        </div>
    </div>
</div>

</body>
</html>
